package com.example.oj.controller;

import com.example.oj.model.Answer;
import com.example.oj.model.OJ;
import com.example.oj.model.Question;
import com.example.oj.service.CheckCodeSafe;
import com.example.oj.service.OJService;
import com.example.oj.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/oj")
@RestController
public class Controller {
    @Autowired
    private OJService ojService;
    @Autowired
    private OJ oj;
    @Autowired
    private Question question;
    @Autowired
    private TaskService taskService;
    @Autowired
    private Answer answer;
    @Autowired
    private CheckCodeSafe checkCodeSafe;
    @RequestMapping("/select")
    public List<OJ> select(){
        return ojService.select();
    }
    @RequestMapping("/selectOne")
    public OJ selectOne(Integer id){
        return ojService.selectOne(id);
    }
    @RequestMapping("/task")
    public Answer task(@RequestBody OJ oj1){
        //获取用户当前工作路径
        System.out.println("用户当前工作路径: " + System.getProperty("user.dir"));
        oj = ojService.selectOne(oj1.getId());
        if (oj == null){
            answer.setError("直接出错");
            answer.setReason("题目不存在");
            return answer;
        }
        String templateCode =oj1.getTemplateCode();
        if (!checkCodeSafe.checkCodeSafe(templateCode)){
            answer.setError("禁止提交");
            answer.setReason("你的想法很危险");
            return answer;
        }
        int index = templateCode.lastIndexOf("}");
        if (index == -1){
            return null;
        }
        String testCode = oj.getTestCode();
        String subCode = oj1.getTemplateCode().substring(0,index);
        String code = subCode + testCode + "\n}";
        System.out.println(code);
        question.setCode(code);
        return taskService.compileAndRun(question);
    }
}
